import { connect } from 'dva'
import { uniqueId } from 'lodash-es'
import { useEffect, useState } from 'react'

import AekTabs from '@/components/AekTabs'
import { loginRoutes } from '@/router/index'
import { getUrlParams, getUrlParamsStr, navigateBack, navigateTo } from '@/router/navigate'
import config from '@/utils/config'

/** 不在后端菜单配置的页面，如详情页 */
const otherMenuMap = {}

const { defaultPageKey } = config

/**
 * 头部导航
 * @param {{
 *    app: import('@/models/app').state
 * }} param0
 */
const TopMenu = ({ app, location }) => {
  const { menuMap, topTabExtraContent } = app

  const [topMenuList, setTopMenuList] = useState([])
  const [selectedTopMenuKey, setSelectedTopMenuKey] = useState()

  let search = location.search
  if (search) {
    const urlParams = getUrlParams(search)
    delete urlParams.action
    delete urlParams.cover
    const urlParamsStr = getUrlParamsStr(urlParams)
    search = urlParamsStr ? '?' + urlParamsStr : ''
  }
  const { pathname } = location
  const pageKey = pathname.split('/').pop()

  useEffect(() => {
    // 将不在系统菜单配置的工程菜单补充进来，如详情页，供头部菜单添加
    loginRoutes.forEach(({ pageKey, name }) => {
      if (menuMap[pageKey]) return
      otherMenuMap[pageKey] = {
        featurePath: pageKey,
        menuName: name,
      }
    })
  }, [])

  const updateTopMenu = () => {
    const find = topMenuList.find(topMenu => topMenu.featurePath === pageKey && topMenu.search === search)
    if (find) {
      setSelectedTopMenuKey(find.topMenuKey)
      return
    }
    if (pageKey === defaultPageKey) {
      setTopMenuList([])
      return
    }
    const { cover } = getUrlParams(location.search)
    // 替换当前页
    if (cover) {
      const _topMenuList = [...topMenuList]
      const find = _topMenuList.find(topMenu => topMenu.topMenuKey === selectedTopMenuKey)
      if (find) {
        const { topMenuName } = getUrlParams(search)
        find.search = search
        find.topMenuName = topMenuName || find.menuName
        setTopMenuList(_topMenuList)
        setSelectedTopMenuKey(find.topMenuKey)
        return
      }
    }

    /** 头部菜单找不到，往头部新增菜单 */
    const menu = menuMap[pageKey] || otherMenuMap[pageKey]
    const _topMenuList = [...topMenuList]
    const topMenuKey = `topMenuKey-${uniqueId()}`
    const { topMenuName } = getUrlParams(search)
    _topMenuList.push({
      ...menu,
      search,
      topMenuKey,
      topMenuName: topMenuName || menu.menuName,
    })
    setTopMenuList(_topMenuList)
    setSelectedTopMenuKey(topMenuKey)
  }

  useEffect(() => {
    if (pathname === '/') return
    updateTopMenu()
  }, [JSON.stringify(location)])

  const onRemove = targetKey => {
    const index = topMenuList.findIndex(({ topMenuKey }) => topMenuKey === targetKey)
    const _topMenuList = [...topMenuList]
    _topMenuList.splice(index, 1)
    setTopMenuList(_topMenuList)
    if (selectedTopMenuKey !== targetKey) return
    const menu = topMenuList[index + 1] || topMenuList[index - 1] || { featurePath: defaultPageKey }
    const { featurePath, search } = menu
    navigateTo(featurePath, getUrlParams(search))
  }

  return (
    topMenuList.length > 0 && (
      <AekTabs
        draggable
        type='editable-card'
        hideAdd
        activeKey={selectedTopMenuKey}
        onChange={async topMenuKey => {
          const { featurePath, search } = topMenuList.find(item => item.topMenuKey === topMenuKey)
          navigateBack(featurePath, getUrlParams(search))
        }}
        onEdit={(targetKey, action) => {
          if (action !== 'remove') return
          onRemove(targetKey)
        }}
        items={topMenuList.map(({ topMenuKey, topMenuName }) => ({
          key: topMenuKey,
          label: topMenuName,
        }))}
        tabBarExtraContent={topTabExtraContent}
      />
    )
  )
}

export default connect(({ app }) => ({
  app,
}))(TopMenu)
